#coding:utf-8
'''
* coder  : dzlua
* email  : 505544956@qq.com
* module : Flask-AuthMgr
* path   : examples
* file   : save.py
* time   : 2017-11-03 14:11:36
'''
#--------------------#
import base
from flask import Flask, g
from flask_auth_mgr import AuthMgr
#--------------------#

#--------------------#
app = Flask(__name__)
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy dog'
auth = AuthMgr(app.config['SECRET_KEY'])
#--------------------#

#--------------------#
users = {
    "john": auth.decode_password("johnpassword"),
    "susan": auth.decode_password("susanpassword")
}

tokens = {
    'refresh_token': {},
    'access_token': {},
    'user_token': {}
}
#--------------------#

#--------------------#
@auth.set_save_token
def save_token(tdata):
    if tdata['type'] == 'user_token':
        email = tdata['data']['email']
        tokens['user_token'][email] = tdata['token']
        return True
    user = tdata['data']['user']
    tp = tdata['type']
    tokens[tp][user] = tdata['token']
    return True
@auth.set_get_token
def get_token(tdata):
    if tdata['type'] == 'user_token':
        email = tdata['data']['email']
        return tokens['user_token'][email]
    user = tdata['data']['user']
    tp = tdata['type']
    return tokens[tp][user]
#--------------------#

#--------------------#
@auth.verify_password
def verify_password(user, pwd):
    g.user = None
    if user not in users:
        return False
    if auth.check_password(users.get(user), pwd):
        g.user = user
        return True
    return False

@auth.verify_refresh_token
def verify_rftoken(token):
    data = auth.refresh_token_data(token)
    if data is None:
        return False
    g.user = data['user']
    return True

@auth.verify_access_token
def verify_atoken(token):
    data = auth.access_token_data(token)
    if data is None:
        return False
    g.user = data['user']
    return True

@auth.verify_user_token
def verify_utoken(token):
    data = auth.user_token_data(token)
    if data is None:
        return False
    g.email = data['email']
    return True
#--------------------#

#--------------------#
base.addroutes(app, auth)
#--------------------#

#--------------------#
if __name__ == '__main__':
    app.run(debug=True)
#--------------------#
